home *** CD-ROM | disk | FTP | other *** search
- Path: macqbl.com.au!usenet
- From: steven@macquarie.com.au (Steven James Brown)
- Newsgroups: comp.lang.c++
- Subject: A curly one for gurus: possible to create a value array of derived objects?
- Date: 15 Feb 1996 05:53:06 GMT
- Organization: Macquarie Bank
- Distribution: world
- Message-ID: <4fuho2$d3s@mblisd.macqbl.com.au>
- Reply-To: steven@macquarie.com.au
- NNTP-Posting-Host: qad10.macqbl.com.au
-
-
- Ok This is a real curly question:
-
- Is it possible to create (and manage) a "value" array of objects from
- derived classes?
-
- E.g:
-
- struct A { virtual char* name() { return "A"; } };
- struct B : public A { int data1; virtual char* name() { return "B"; } };
- struct C : public A { double data2; virtual char* name() { return "C"; } };
-
- To be able to provide access to an array of B's and C's without occuring
- the overhead of pointer indirection, I am hoping it is somehow possible to
- have something like:
-
- #include <stdio.h>
- main()
- {
- A* a = new A[10];
- B b;
- C c;
-
- a[0] = b;
- a[1] = c;
-
- printf("%s\n", a[0].name());
- printf("%s\n", a[1].name());
- }
-
-
- The output from this (as you may have already guessed) is
- A
- A
-
- and not
- B
- C
-
- The problem here is I guess "data slicing" and the use of the default operator=.
- Is it possible to somehow get over this
- by faking a union? I can't use unions in practice because my derived classes
- have (default) constructors.
-
- The idea for this came from the "Composite" pattern in the Design Patterns
- book by Gamma/Helm/Johnson/Vlissides. The "A" class above being the "Composite"
- object, and the "B" and "C" being the "Component" objects.
-
- Thanks for any solutions/suggestions you can provide.
- Steve
- ---
-
- ////////////////////////////////////////////////////////////////////////////
- // Steven James Brown Disclaimer: Any comments or //
- // Qantitative Applications views made are my own and are //
- // Macquarie Bank Limited unrelated to those of my //
- // steven@macquarie.com.au employer. //
- // //
- ////////////////////////////////////////////////////////////////////////////
-
-
-
-